import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Select, Space } from 'antd';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safeHazardInfoAdd,
  safeHazardInfoUpdate
} from '@/services/bizApi/anquanyinhuanxinxijiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const submit = useRequest(
    async ({ _type, dueTime, ...values }) => {
      const query = {
        ...values,
        dueTime: dueTime ? dayjs(dueTime).format('YYYY-MM-DD HH:mm:ss') : undefined,
        inspectionUserName: userInfo?.data?.filter(
          (item) => item.id === values?.inspectionUserId
        )?.[0]?.fullName,
        inspectionUnitName: (store.dict['inspectUnit'] || [])?.filter(
          (item) => item?.dicValue === values?.inspectionUnitId
        )?.[0]?.dicName,
        inspectedUnitName: (store.dict['inspectedUnit'] || [])?.filter(
          (item) => item?.dicValue === values?.inspectedUnitId
        )?.[0]?.dicName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? safeHazardInfoUpdate(query) : safeHazardInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              dueTime: arg?.rowData?.dueTime ? dayjs(arg?.rowData?.dueTime) : undefined
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="隐患单号"
          name="no"
          rules={[
            {
              required: true,
              message: '请输入隐患单号'
            }
          ]}
        >
          <Input placeholder="请输入隐患单号" />
        </Form.Item>
        <Form.Item
          label="隐患名称"
          name="name"
          rules={[
            {
              required: true,
              message: '请输入隐患名称'
            }
          ]}
        >
          <Input placeholder="请输入隐患名称" />
        </Form.Item>
        <Form.Item
          label="隐患类型"
          name="type"
          rules={[
            {
              required: true,
              message: '请选择隐患类型'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择隐患类型"
            options={[
              {
                label: '安全隐患',
                value: 1
              },
              {
                label: '环保隐患',
                value: 2
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="隐患内容"
          name="content"
          rules={[
            {
              required: true,
              message: '请输入隐患内容'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入隐患内容" />
        </Form.Item>
        <ProFormSelect
          name="inspectionUserId"
          label="检查人员"
          placeholder="请选择检查人员"
          showSearch={true}
          rules={[{ required: true, message: '请选择检查人员' }]}
          request={async () => {
            const res = await orgUserInfoVoPage({ page: 1, size: 1000 });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <ProFormSelect
          name="inspectionUnitId"
          label="检查单位"
          placeholder="请选择检查单位"
          rules={[{ required: true, message: '请选择检查单位' }]}
          request={async () => {
            return (
              (store.dict['inspectUnit'] || []).map((item) => ({
                value: item.dicValue,
                label: item.dicName
              })) || []
            );
          }}
        />
        <ProFormSelect
          name="inspectedUnitId"
          label="受检单位"
          placeholder="请选择受检单位"
          rules={[{ required: true, message: '请选择受检单位' }]}
          request={async () => {
            return (
              (store.dict['inspectedUnit'] || []).map((item) => ({
                value: item.dicValue,
                label: item.dicName
              })) || []
            );
          }}
        />
        <Form.Item
          label="整改截止时间"
          name="dueTime"
          rules={[
            {
              required: true,
              message: '请选择整改截止时间'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} showTime placeholder="请选择整改截止时间" />
        </Form.Item>
        <Form.Item
          label="整改建议"
          name="suggestion"
          rules={[
            {
              required: false,
              message: '请输入整改建议'
            }
          ]}
        >
          <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="请输入整改建议" />
        </Form.Item>
        <Form.Item
          label="整改附件"
          name="attachment"
          rules={[
            {
              required: false,
              message: '请上传整改附件'
            }
          ]}
        >
          <Upload
          // base64
          //  accept="image/*"
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
        {args?.type === 'detail' && (args.rowData.status === 5 || args.rowData.status === 6) && (
          <>
            <Form.Item
              label="验收结果"
              name="status"
              rules={[
                {
                  required: true,
                  message: '请选择验收结果'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="请选择验收结果"
                options={[
                  {
                    label: '验收通过',
                    value: 5
                  },
                  {
                    label: '验收失败',
                    value: 6
                  }
                ]}
              />
            </Form.Item>
            <Form.Item
              label="验收附件"
              name="acceptanceAttachment"
              rules={[
                {
                  required: false,
                  message: '请上传验收附件'
                }
              ]}
            >
              <Upload
              // base64
              //  accept="image/*"
              >
                <Button>上传</Button>
              </Upload>
            </Form.Item>
          </>
        )}
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
